//
//  ComposeViewController.swift
//  我的微博
//
//  Created by ZhangChao on 15/9/10.
//  Copyright © 2015年 ZhangChao. All rights reserved.
//

import UIKit

class ComposeViewController: UIViewController , UITextViewDelegate{

    // 工具栏底部的约束
    private var toolBarBottomCons : NSLayoutConstraint?
    
    // 文本视图的底部约束
    private var textViewBottomCons : NSLayoutConstraint?
    
    // 照片选择器的顶部视图
    private var pictureViewHeightCons : NSLayoutConstraint?

    // 取消按钮
    @objc private func cancleBtnClick(){
        
        // 取消键盘
        //        textView.endEditing(true) // 这俩句话 效果一样
        textView.resignFirstResponder()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    // 完成按钮点击
    @objc private func doneBtnClick (){
        
        
    }
    // 添加图片按钮
    @objc private func selectPicture (){
        // 1.删除picture和toolBar 的约束
        view.removeConstraint(textViewBottomCons!)
        
        // 2.重新添加约束
        textViewBottomCons = NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: pictureSelectorViewController.view, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0)
        view.addConstraint(textViewBottomCons!)
        
        // 3.添加约束和弹出动画
        pictureViewHeightCons?.constant = UIScreen.mainScreen().bounds.height * 0.6
        
        // 4.动画前先关闭键盘
        textView.resignFirstResponder()
        
        UIView.animateWithDuration(0.25) { () -> Void in
            
            self.view.layoutIfNeeded()
        }
        
    }
    // 键盘通知
    @objc private func keyboardChanged(notifaction : NSNotification){
        
//        printLog(notifaction)
        
        let rect = notifaction.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
       
        // 解决动画不同步的问题
        let duration = notifaction.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
        // 解决toolBar不能跳下来的问题
        toolBarBottomCons?.constant = -UIScreen.mainScreen().bounds.height + rect.origin.y
        
        // 添加动画
        UIView.animateWithDuration(duration) { () -> Void in
            
            self.view.layoutIfNeeded()
        }
        
    }
    override func loadView() {
        view = UIView()// 这里必须初始化 因为没有调用父类的loadView
        
        view.backgroundColor = UIColor.whiteColor()
        
        // 先添加textView 然后添加 toolBar 会出现textView向下移动64个点得现象,
        // 解决:取消scrollView的自动缩进
        automaticallyAdjustsScrollViewInsets = false
        
        perpareNav()
        perpareTextView()
        perpareToolBar()
        preparePictureSelector()
    }
    // 生命周期方法,进入界面就开始编辑模式
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        // 判断,当用户选择照片的时候让键盘不弹出
        if pictureViewHeightCons?.constant == 0{
            
            textView.becomeFirstResponder()
        }
    }
    
    override func viewDidLoad() {
        // 获取键盘的通知(这个通知在UIWindow的倒数第二行)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    
    // 定义导航条
    private func perpareNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancleBtnClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "完成", style: UIBarButtonItemStyle.Plain, target: self, action: "doneBtnClick")
        // 禁用完成按钮
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 添加标题视图
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 32))
        
        let titleLabel = UILabel(title: "发微博", color: UIColor.darkGrayColor(), fontSize: 16)
        let nameLabel = UILabel(title: UserAccountViewModel.sharedUserAccount.userAccount?.name, color: UIColor.lightGrayColor(), fontSize: 12)
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        titleLabel.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
//        nameLabel.ff_AlignVertical(type: ff_AlignType.BottomCenter, referView: titleLabel, size: nil) // 上下俩句话都可以
        nameLabel.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
        // 添加
        navigationItem.titleView = titleView
        
    }
    
    // 定义输入框
    private func perpareTextView(){
        view.addSubview(textView)
        
        // 测试使用
//        textView.text = "写点什么东西..."
        // 自动布局
        textView.translatesAutoresizingMaskIntoConstraints = false
        
        let viewDict = ["tb":toolBar,"tv":textView,"top":topLayoutGuide]
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tv]-0-|", options: [], metrics: nil, views: viewDict as! [String : AnyObject]))
        
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[top]-0-[tv]-0-[tb]", options: [], metrics: nil, views: viewDict as! [String : AnyObject]))
        
        // 删除一个tv和tb之间的约束
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[top]-0-[tv]", options: [], metrics: nil, views: viewDict as! [String : AnyObject]))
        
        // 重新定义textView和toolBar的约束,并记录约束
        textViewBottomCons = NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: toolBar, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0)
        view.addConstraint(textViewBottomCons!)
        
        // 添加占位label
        textView.addSubview(placeHolderLabel)
        
        placeHolderLabel.frame = CGRectMake(5, 8, placeHolderLabel.bounds.width, placeHolderLabel.bounds.height)
        
    }
    
    // 定义工具栏
    private func perpareToolBar(){
        view.addSubview(toolBar)
        
        // 设置toolBar的背景颜色
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        // 设置自动布局
        let w = UIScreen.mainScreen().bounds.width
        let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: w, height: 36))
        
        // 记录toolBar的底部约束
        toolBarBottomCons = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        // 定义按钮数组
        let itemSettings = [["imageName":"compose_toolbar_picture","action":"selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background"],
            ["imageName": "compose_addbutton_background"]]
        
        // 添加按钮
        var items = [UIBarButtonItem]()
        
        for dict in itemSettings {
            
            // 用分类添加barButtonItem
            items.append(UIBarButtonItem(imageName:dict["imageName"]!, target: self, actionName: dict["action"]))
            // 在每个按钮中间加一个弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        // 这里会多出来一个,去掉最后一个弹簧
        items.removeLast()
        
        toolBar.items = items
    }
    
    // 定义图片选择界面
    private func preparePictureSelector(){
        // 出现问题,点一下+按钮就会界面就会消失
        //        .sb中有一个containerView,纯代码中没有这个控件
        //        .本质上就是一个UIView,他做了以下俩种工作
        //        .1>addSubView(vc.view)
        //        .2>addChildViewController(vc)
        
        addChildViewController(pictureSelectorViewController)
        
        // 出现问题:toolBar被挡住了
//        view.addSubview(pictureSelectorViewController.view)
        
        view.insertSubview(pictureSelectorViewController.view, belowSubview: toolBar)
        
        
        // 自动布局
        let w = UIScreen.mainScreen().bounds.size.width
//        let h = UIScreen.mainScreen().bounds.size.height * 0.6
        let h = 0
        
        let cons = pictureSelectorViewController.view.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: w, height: CGFloat (h)))
        
        // 记录照片约束的高度约束
        pictureViewHeightCons = pictureSelectorViewController.view.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
    }
    
    // textViewDelegate 
    func textViewDidChange(textView: UITextView) {

        // 有字符的时候让placeHolderLabel隐藏
        placeHolderLabel.hidden = textView.hasText()
        
        // 有字符的时候让右边的item可以点击
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    
    }
    
    // 懒加载textView
    private lazy var textView : UITextView = {
        
        let textView = UITextView()
        
        textView.textColor = UIColor.darkGrayColor()
        textView.font = UIFont.systemFontOfSize(18)
        
        // 设置textView可以垂直方向拖动
        textView.alwaysBounceVertical = true
        
        // 遵守代理协议
        textView.delegate = self
        
        // 拖拽的时候取消键盘
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        return textView
        
    }()
    // 工具栏
    private lazy var toolBar = UIToolbar()
    
    // placeHolder
    private lazy var placeHolderLabel : UILabel = UILabel(title: "写点什么东西...", color: UIColor.darkGrayColor(), fontSize: 18)
    
    // 照片选择器
    private lazy var pictureSelectorViewController = PictureSelectorViewController()
}



